package com.digitalchina.dcn.dcss.web.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.digitalchina.dcn.dcss.core.generic.GenericDao;
import com.digitalchina.dcn.dcss.core.generic.GenericServiceImpl;
import com.digitalchina.dcn.dcss.web.dao.RoleMapper;
import com.digitalchina.dcn.dcss.web.model.User;
import com.digitalchina.dcn.dcss.web.service.ResourceService;
import com.digitalchina.dcn.dcss.web.service.RoleService;
import com.digitalchina.dcn.dcss.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.digitalchina.dcn.dcss.web.model.Role;

/**
 * 角色Service实现类
 *
 * @author StarZou
 * @since 2014年6月10日 下午4:16:33
 */
@Service
public class RoleServiceImpl extends GenericServiceImpl<Role, Long> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ResourceService resourceService;

    @Override
    public GenericDao<Role, Long> getDao() {
        return roleMapper;
    }

    @Override
    public List<Role> selectRolesByUserId(Long userId) {
        User user = userService.selectById(userId);
        List<Role> roleList = new ArrayList<Role>();
        for (Long roleId : user.getRoleIds()) {
            Role role = roleMapper.selectByPrimaryKey(roleId);
            if (role != null && !roleList.contains(role)) {
                roleList.add(role);
            }
        }

        return roleList;
   }

    public Role createRole(Role role) {
        roleMapper.insert(role);
        return roleMapper.findByRoleName(role.getRole());
    }

    public Role updateRole(Role role) {
        roleMapper.updateByPrimaryKey(role);
        return roleMapper.selectByPrimaryKey(role.getId());
    }

    public void deleteRole(Long roleId) {
        roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public Role findOne(Long roleId) {
        return roleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    @Override
    public Set<String> findRoles(Long... roleIds) {
        Set<String> roles = new HashSet<String>();
        for(Long roleId : roleIds) {
            Role role = findOne(roleId);
            if(role != null) {
                roles.add(role.getRole());
            }
        }
        return roles;
    }

    @Override
    public Set<String> findPermissions(Long[] roleIds) {
        Set<Long> resourceIds = new HashSet<Long>();
        for(Long roleId : roleIds) {
            Role role = findOne(roleId);
            if(role != null) {
                resourceIds.addAll(role.getResourceIds());
            }
        }
        return resourceService.findPermissions(resourceIds);
    }

}
